# -*- coding: utf-8 -*-
"""
@Time ： 2020/11/2 21:02
@Auth ： Mr. William 1052949192
@Company ：特斯汀学院 @testingedu.com.cn
@Function ：qq滑动验证码识别
"""
import time

from selenium import webdriver
import requests
import cv2
from selenium.webdriver import ActionChains

driver = webdriver.Chrome()
driver.maximize_window()
driver.implicitly_wait(10)
driver.get('http://i.qq.com')

driver.switch_to.frame(driver.find_element_by_xpath('//*[@id="login_frame"]'))
driver.find_element_by_xpath('//*[@id="switcher_plogin"]').click()
driver.find_element_by_xpath('//*[@id="u"]').send_keys('1541561')
driver.find_element_by_xpath('//*[@id="p"]').send_keys('34324234')
driver.find_element_by_xpath('//*[@id="login_button"]').click()
driver.switch_to.frame(driver.find_element_by_xpath('//*[@id="tcaptcha_iframe"]'))

while True:
    # 下载背景原图和模块原图
    # 背景图
    ele_target = driver.find_element_by_xpath('//*[@id="slideBg"]')
    ele_template = driver.find_element_by_xpath('//*[@id="slideBlock"]')
    target_src = ele_target.get_attribute('src')
    template_src = ele_template.get_attribute('src')

    # 下载
    target_img = requests.get(target_src).content
    with open('./imgs/target.png', mode='wb') as f:
        f.write(target_img)
    f.close()

    template_img = requests.get(template_src).content
    with open('./imgs/template.png', mode='wb') as f:
        f.write(template_img)
    f.close()

    w1 = ele_target.size['width']

    # 打开背景图
    target_rgb = cv2.imread('./imgs/target.png')
    w2 = target_rgb.shape[1]
    # 灰度处理
    target_gray = cv2.cvtColor(target_rgb, cv2.COLOR_BGR2GRAY)
    # 打开模板图
    template_rgb = cv2.imread('./imgs/template.png', 0)
    # 获取模板在背景图的位置
    res = cv2.matchTemplate(target_gray, template_rgb, cv2.TM_CCOEFF_NORMED)
    # 获取最好和最差的匹配
    value = cv2.minMaxLoc(res)
    x = value[2][0] + 23
    # 计算缩放之后的x距离
    x = int(x * w1 / w2) - 32
    print('左边界：%d' % x)

    # 滑动
    action = ActionChains(driver)
    action.click_and_hold(ele_template).perform()
    action.move_by_offset(x, 0).perform()
    action.release().perform()
    time.sleep(2)
    try:
        driver.implicitly_wait(3)
        ele = driver.find_element_by_xpath('//*[@id="e_reload"]')
        ele.click()
    except Exception as e:
        driver.implicitly_wait(10)
        break

    driver.implicitly_wait(10)


